package com.dk.service.impl;

import com.dk.mapper.PersonRoleMapper;
import com.dk.mapper.TPersonMapper;
import com.dk.mapper.TRoleMapper;
import com.dk.pojo.PersonRoleExample;
import com.dk.pojo.TPerson;
import com.dk.pojo.TPersonExample;
import com.dk.pojo.TRole;
import com.dk.service.PersonService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@DubboService
@Service
public class PersonServiceImpl implements PersonService {

    @Autowired
    private TPersonMapper tPersonMapper;

    @Autowired
    private PersonRoleMapper personRoleMapper;

    @Autowired
    private TRoleMapper tRoleMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public TPerson selectInfo(String pname) {

        TPersonExample te = new TPersonExample();

        TPersonExample.Criteria criteria = te.createCriteria();

        criteria.andPnameEqualTo(pname);

        List<TPerson> list = tPersonMapper.selectByExample(te);

        return list.size() > 0 ? list.get(0) : null;
    }

    @Override
    public List<TPerson> getInfo() {

        return tPersonMapper.selectByExample(null);
    }

    @Override
    public boolean deleteInfo(Integer pid) {

        personRoleMapper.deleteByPid(pid);

        redisTemplate.opsForHash().delete("permission","menu:info:"+pid);

        return tPersonMapper.deleteByPrimaryKey(pid) > 0;
    }

    @Override
    public List<TRole> toAdd() {

        List<TRole> list = tRoleMapper.selectByExample(null);

        return list;
    }

    @Override
    public boolean insertInfo(TPerson tPerson, Integer[] roleId) {

        int i = tPersonMapper.insertInfo(tPerson);

        int i2 = personRoleMapper.inserBach(tPerson.getPid(),roleId);

        return true;
    }

    @Override
    public List<TRole> getRoleInfo() {

        List<TRole> list = tRoleMapper.selectByExample(null);

        return list;
    }

    @Override
    public TPerson selectInfoById(Integer pid) {

        TPerson tPerson =tPersonMapper.selectByPrimaryKey(pid);

        return tPerson;
    }

    @Override
    public List<Integer> getRoleById(Integer pid) {

        return personRoleMapper.getRoleById(pid);
    }

    @Override
    public boolean updateInfoById(TPerson tPerson, Integer[] roleId) {

        tPersonMapper.updateByPrimaryKeySelective(tPerson);

        PersonRoleExample pe = new PersonRoleExample();

        PersonRoleExample.Criteria criteria = pe.createCriteria();

        criteria.andPersonIdEqualTo(tPerson.getPid());

        personRoleMapper.deleteByExample(pe);

        redisTemplate.opsForHash().delete("permission","menu:info:"+tPerson.getPid());

        personRoleMapper.inserBach(tPerson.getPid(),roleId);

        return true;
    }
}
